from http import HTTPStatus
# 建议dashscope SDK 的版本 >= 1.14.0
from dashscope import Application
import asyncio
import websockets
import json
import os
import ssl
SSL_PRIVATE_KEY = 'C:/Users/local/nginx/conf/cert/ai.ldjyypt.cn.key'
SSL_CERTIFICATE = 'C:/Users/local/nginx/conf/cert/ai.ldjyypt.cn_bundle.pem'
 
# 确保SSL证书和私钥文件存在
assert os.path.exists(SSL_PRIVATE_KEY)
assert os.path.exists(SSL_CERTIFICATE)

ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_context.load_cert_chain(certfile=SSL_CERTIFICATE, keyfile=SSL_PRIVATE_KEY)

async def call_agent_app(websocket, path):
    name = await websocket.recv()
    data = json.loads(name)
    appid = data.get('appid')
    message = data.get('message')
    responses = Application.call(app_id=appid,
                                prompt=message,
                                stream=True,
                                incremental_output=True
                                )
    for response in responses:
        if response.status_code == HTTPStatus.OK:
            await asyncio.sleep(0.1)  
            print(response.output)
            await websocket.send(json.dumps(response.output))
        else:
            print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
                response.request_id, response.status_code,
                response.code, response.message
            ))
# start_server = websockets.serve(call_agent_app, "0.0.0.0",5000)
start_server = websockets.serve(call_agent_app, "0.0.0.0",5000,ssl=ssl_context)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()